<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2019/1/7
 * Time: 13:32
 */

namespace api\storage\service\output;


use api\storage\common\FileDataTemplate;
use api\storage\model\BomDetailModel;
use api\storage\model\BomModel;

class LocalOutputService extends BaseOutputService
{

    public function getLackMateriel($bomUuid, $supplierId)
    {
        $result = $this->bomDetailModel->queryLocalLackMateriel($bomUuid)->toArray();
        $cache = [];
        foreach ($result as $item) {
            $cache[$item['sub_materiel_id']] = FileDataTemplate::outputRecordData($item['ocount'],$item['count']);
        }
        return $this->returnPreviousProcessMaterielTemplate($result, $cache);
    }

    public function getBomMateriel($bomUuid, $supplierId)
    {
        $result = $this->bomDetailModel->queryBomByUuid($bomUuid)->toArray();
        $cache = [];
        foreach ($result as $item) {
            $cache[$item['sub_materiel_id']] = FileDataTemplate::outputRecordData($item['count'],$item['count']);
        }
        return $this->returnPreviousProcessMaterielTemplate($result, $cache);
    }

    public function handleComplete($bomId, $data, $supplierId, $bomUuid)
    {
        $flag = true;
        $logStr = "计算库存===>出库单：" . $bomId . "，物料号：%s,多出/少出数量：%d";
        $bomDetailModel = new BomDetailModel();
        foreach ($data['recordData'] as $materielId => $item) {
            $count = $item['currentCount'] - $item['planCount'];
            if ($flag) {
                $flag = $count < 0 ? false : true;
            }
            $bomDetailModel->updateDetail($bomUuid, $materielId, ['flag' => $count]);
            $this->logger->debug(sprintf($logStr, $materielId, $count));
        }
        $bomModel = new BomModel();
        if ($flag == true) {
            $this->logger->debug("出库单：{$bomId}，标记为完成");
            $bomModel->updateBom($bomUuid, ['status' => 1]);
            $bomDetailModel->updateCleanCount($bomUuid);
        } else {
            $this->logger->debug("出库单：{$bomId}，标记为欠料");
            $bomModel->updateBom($bomUuid, ['status' => 2]);
        }
    }


}